package com.eduagent.xwqeduagent.api.characterRecognition.PhotographySpeedCalculation.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * 拍照速算识别API签名工具类
 */
public class SignUtil {

    /**
     * 对请求体进行SHA-256加密后Base64编码
     * 
     * @param body 请求体字符串
     * @return Base64编码的SHA-256摘要
     */
    public static String signBody(String body) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(body.getBytes(StandardCharsets.UTF_8));
            encodeStr = Base64.getEncoder().encodeToString(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("签名时出现异常: SHA-256算法不可用", e);
        }
        return encodeStr;
    }

    /**
     * 使用HMAC-SHA256算法对签名原文进行签名
     * 
     * @param signature 签名原文
     * @param apiSecret API密钥
     * @return Base64编码的HMAC-SHA256签名结果
     */
    public static String hmacSign(String signature, String apiSecret) {
        Charset charset = StandardCharsets.UTF_8;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(charset), "HmacSHA256");
            mac.init(spec);
            byte[] hexDigits = mac.doFinal(signature.getBytes(charset));
            return Base64.getEncoder().encodeToString(hexDigits);
        } catch (Exception e) {
            throw new RuntimeException("HMAC-SHA256签名异常", e);
        }
    }
} 